import io
from django_redis import get_redis_connection
from django.http import HttpResponse
from django.views import View
from rest_framework_simplejwt.views import TokenObtainSlidingView
from config.dbs.redisconfig import LOGIN_VERIFY_CODE_TEMPLATE,EXPIRE_TIME
from utils.verifyUtil import ImageVerify
from .serializers import MyTokenSerializer
# Create your views here.


class MyTokenViews(TokenObtainSlidingView):
    serializer_class = MyTokenSerializer



class ImageVerifyView(View):
    def get(self,request,uuid):     # 获取图形验证码
        imgVerify = ImageVerify()
        img, code = imgVerify.image_code()
        bytes_box= io.BytesIO()       #创建一个字节流管道
        img.save(bytes_box,format('PNG'))  # 将图片以png格式保存到管道
        image_bytes = bytes_box.getvalue()

        cache = get_redis_connection(alias='verify_codes')
        cache.set(LOGIN_VERIFY_CODE_TEMPLATE % uuid, code, EXPIRE_TIME)

        return HttpResponse(image_bytes,content_type='image/png')

